package com.dme.modules.service.person.impl;

import com.dme.modules.dao.person.PersonDao;
import com.dme.modules.entity.Person;
import com.dme.modules.service.person.PersonService;
import com.dme.modules.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: 喜欢编程的代先生
 * @Date: 2022-06-19 17:42
 * @Description: 拒绝侵权
 */
@Service
public class PersonServiceImpl implements PersonService {

    private PersonDao personDao;

    @Autowired
    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

    @Override
    public void insertBatch(List<Person> list) {
        list.parallelStream().forEach(person -> {
            personDao.insert(person);
        });
    }

    @Override
    public void updateBatchByNormal(List<Person> persons) {
        for (Person person : persons) {
            personDao.updateById(person);
        }
    }

    @Override
    public void updateBatchByThread(List<Person> persons) {
        List<List<Person>> divide = ListUtils.divide(persons, 20);
        CountDownLatch downLatch = new CountDownLatch(divide.size());
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        for (List<Person> list : divide) {
            threadPool.execute(() -> {
                System.out.println("线程开始执行......." + Thread.currentThread().getName());
                for (Person person : list) {
                    personDao.updateById(person);
                }
                System.out.println("线程结束执行......." + Thread.currentThread().getName());
                downLatch.countDown();
            });
        }
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Person> selectList(){
        List<Person> people = personDao.selectList(null);
        return people;
    }
}
